<?php

class SearchAction extends Action {
  //1-法律法规,2-标准,3-新闻事故,4-文档,5-视频,6-用户,7-群组,8-帖子,9-博文

  private $_search = array(
    1=>array(
        select=>"id,ltitle as title,ldate_pub as datetime",order=>"order by datetime desc",table=>'a_law',
        index=>"law_index",total=>array("zy_id","hy_id","dq_id","lawtype_id"),total_table=>array("a_zy","a_hy","a_region","a_lawtype"),
        detail_url=>"http://www.ehs.cn/law-detail.php?id=",
        tpl=>'index',
        match_fields=>array('title'),
        title=>'法律法规'
    ),
    2=>array(
        select=>"id,title,FROM_UNIXTIME(add_time) as datetime",order=>"order by datetime desc",table=>'bz',
        index=>"bz_index",total=>array("type_id"),total_table=>array("bz_type"),
        detail_url=>"__APP__/bz/index/id/",
        tpl=>'index',
        match_fields=>array('title'),
        title=>'标准'
    ),
    3=>array(
        select=>"id,title,FROM_UNIXTIME(newstime) as datetime",order=>"order by datetime desc",table=>'phome_ecms_news',
        index=>"news_index",total=>array("classid","idd","lawtype_id"),total_table=>array("a_zy","a_hy","a_lawtype"),
        detail_url=>"http://www.ehs.cn/",
        tpl=>'index',
        match_fields=>array('title'),
        title=>'新闻'
    ),
    //1-法律法规,2-标准,3-新闻事故,4-文档,5-视频,6-用户,7-群组,8-帖子,9-博文
    4=>array(
        select=>"id,title,FROM_UNIXTIME(add_time) as datetime",order=>"order by datetime desc",table=>'a_doc',
        index=>"doc_index",total=>array("zy_id","hy_id"),total_table=>array("a_zy","a_hy"),
        detail_url=>"http://www.ehs.cn/doc-detail.php?id=",
        tpl=>'index',
    ),
    5=>array(
        select=>"vid as id,title,FROM_UNIXTIME(datetime) as datetime",order=>"order by datetime desc",table=>'oj_admin_video',
        index=>"video_index",total=>array("zy_id"),total_table=>array("a_zy"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'index',
        match_fields=>array('title'),
        title=>'文档'
    ),
    5=>array(
        select=>"vid as id,title,FROM_UNIXTIME(datetime) as datetime",order=>"order by datetime desc",table=>'oj_admin_video',
        index=>"video_index",total=>array("zy_id"),total_table=>array("a_zy"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'index',
        match_fields=>array('title'),
        title=>'视频'
    ),
    //1-法律法规,2-标准,3-新闻事故,4-文档,5-视频,6-用户,7-群组,8-帖子,9-博文
    6=>array(//用户
        select=>"uid,username,introduce,icon,regdate",order=>"order by username ASC",table=>'pw_members',
        index=>"member_index",total=>array("zy_id"),total_table=>array("pw_members"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'search-list-member',
        match_fields=>array('username'),
        title=>'用户'
    ),
    7=>array(//群组
        select=>"id,admin,cname,members,cnimg as icon,createtime",order=>"",table=>'pw_colonys',
        index=>"colonys_index",total=>array("zy_id"),total_table=>array("a_zy"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'search-list-group',
        match_fields=>array('cname'),
        title=>'群组'
    ),
    8=>array(//帖子
        select=>"a_pw_colonys_article.id,cyid,content,a_pw_colonys_article.uid,title,username,create_time",order=>"",table=>'a_pw_colonys_article',
        index=>"article_index",total=>array("zy_id"),total_table=>array("a_zy"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'search-list',
        match_fields=>array('title','content'),
        title=>'群组帖子'
    ),
    9=>array(//博文
        select=>"did,pw_diary.uid,content,pw_diary.username,subject,postdate",order=>"",table=>'pw_diary',
        index=>"diary_index",total=>array("zy_id"),total_table=>array("a_zy"),
        detail_url=>"__APP__/docVideos/index/id/",
        tpl=>'search-list',
        match_fields=>array('subject','content'),
        title=>'个人博文'
    )
  );

  private $_uid=0;

  function _initialize() {
    $this->assign("istp", 1);//TP和PHPWIND都用到，加上这个参数进行区别
    $this->_uid=empty($_COOKIE['tpxslmluserid'])?0:$_COOKIE['tpxslmluserid'];
  }


  public function index() {

    $type = $_GET['type'];
    $content = $_GET['content'];
    $search = $this->_search[$type];
    $index = $search["index"];
    import("@.ORG.Sphinxapi"); //导入Sphinxapi
    $cl = new SphinxClient ();
    $cl->SetServer('127.0.0.1', 9312);
    $cl->SetConnectTimeout(3);
    $cl->SetArrayResult(true);
    $cl->SetMatchMode(SPH_MATCH_EXTENDED);
	//$cl->SetMatchMode(SPH_MATCH_PHRASE);
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $count = $this->_getSearchCount($cl,$content,$index);
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();

    //高亮处理
    $list = $this->_getSearchList($cl,$content,$index,$p->firstRow,$p->listRows,$type);


    $this->assign("search_content", $content);
    $this->assign("records",$records);
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign('keyWord',$content);
    $this->assign('title',$search['title']);
    $this->assign('type',$type);
    //$leftMenu = $this->_formatLeftMenu($result);
    //dump($list);
    $this->display($search['tpl']);
  }

  //根据输入的内容和索引，找出结果总数
  private function _getSearchCount($cl,$content,$index) {
    $result = $cl->Query($content, $index);
    $count = $result['total'];
    return $count;
  }

  /*  params  $cl:        SphinxClient
   *  params  $content:   需要查找的内容
   *  params  $index：    对应查找的索引
   *  params  $page:      页数
   *  params  $records:   每页显示多少条记录
   *  params  $type:      1-法律法规,2-标准,3-新闻事故,4-文档,5-视频,6-图片
   *  return  $list
   *  */
  private function _getSearchList($cl,$content,$index,$page,$records,$type) {
    $cl->SetLimits($page,$records);
    $cl->SetSortMode(SPH_SORT_EXTENDED,"@id desc");
    $result = $cl->Query($content,$index);
    $matches = $result['matches'];
    $ids = array();
    foreach ($matches as $k => $v) {
      $ids[] = $v['id'];
    }
    if(!count($ids))
      $ids=array(0);

    $m = M();
    $search = $this->_search[$type];
    $id = ($type == 5)?"vid":"id";
    if($type==6)$id='uid';//会员搜索
    if($type==9)$id='did';//会员搜索


    if(!in_array($type,array(3,7,8,9))) {
      $sql = "select ".$search["select"]." from ".$search['table']." where $id in (".implode(',', $ids).") ".$search['order'];
    }else {
      if($type == 3)//新闻特殊处理
        $sql = "select title,date_time as datetime,filepath as id from v_articlepath where $id in (".implode(',', $ids).") ".$search['order'];
      if($type==7)	 //群组
        $sql="select ".$search["select"].",uid from ".$search['table'].",pw_members where pw_colonys.admin=pw_members.username AND  $id in (".implode(',', $ids).") ".$search['order'];
      if($type==8)//帖子
        $sql = "select ".$search["select"]." ,cnimg as icon from ".$search['table'].",pw_colonys where a_pw_colonys_article.cyid=pw_colonys.id AND a_pw_colonys_article.$id in (".implode(',', $ids).")";
      if($type==9) //博文
        $sql = "select ".$search["select"]." ,icon from ".$search['table'].",pw_members where pw_diary.uid=pw_members.uid AND $id in (".implode(',', $ids).")";
    }

    $list = $m->query($sql);
    //
    foreach ($list as $k => $l) {
      $list[$k]['detail_url'] = $search['detail_url'].$l['id'];
      if($type!=6)$list[$k]['datetime'] = substr($l['datetime'],0,10);
    }
    if($type==6 || $type==9) {//格式化头像
      //echo $m->getLastSQL();
      $member=D('PwMembers');
      $member->getIconByList($list);
      //dump($list);
    }
    if($type==6) {//会员
      $m2=M('PwFriends');
      foreach($list as &$li) {
        $item=$m2->where("uid={$this->_uid} and friendid={$li['uid']}")->find();
        $li['isFriend']=!empty($item);
      }
    }

    if($type==7) {//群组
      $member=D('PwMembers');
      $article=M('APwColonysArticle');
      $member->getIconByList($list);
      foreach($list as &$li) {
        $m2=D('PwMembers');
        $li['isMember']=$m2->isColonyMember($this->_uid,$li['id']);
        $count=$article->where("cyid={$li['id']}")->count();
        $li['aNum']=$count;
      }
    }
    
	//dump($list);
    /*if($type==8 || $type==9){
	   foreach($list as &$li){
		  $li['content']=$this->utf8Substr(strip_tags($li['content']),0, 100).'...';
	   }	 
	 }*/
    //高亮处理
    if(is_array($search['match_fields'])) {
	  
      foreach($list as &$li) {
        foreach($search['match_fields'] as $field) {//echo $field;
          $back=$cl->BuildExcerpts (array(strip_tags($li[$field])),//排除html标签影响
            $index, //索引名称
            $content, //搜索关键词
            $opts=array("around"=>30,"before_match"=>'<font style="color:red">','after_match'=>'</font>')
          );
          $li[$field]=$back[0];
		  //echo $li[$field].'<br>';
        }
      }

    }

    return $list;
  }

  //截取utf8字符串
  private function utf8Substr($str, $from, $len) {
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
      '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
      '$1',$str);
  }

  //格式化搜索结果，目的用于构建左边的菜单
  public function _formatLeftMenu($result) {
    return "";
  }

}
?>
